using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.CustomControls;
using ctsu.Data;
using ctsu.Security;
using ctsu.Shared;
using Microsoft.Practices.EnterpriseLibrary.Data;

using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Tools;

namespace ctsu.Admin.BusLogic
{

	public class BLFormProtocolImpl : BLFormBaseImpl
	{
		//for printing        
		private PrintDialog _pDlg;
		private PrintDocument _pDoc;
		private int _page;
		private int _startRow;
		private DataGrid _dgPrint;
		private DataTable _dtPrint;
		private string _subTitle;

		#region control references
		private UserGrid _protocolStaff;
		private bool _isExistsVisits;
		protected CheckBox _active;
		protected CheckBox _incomplete;
		protected Button _btnAddInvetig;
		protected TextBox _id;
		protected TextBox _actualPatients;
		protected TextBox _actualAdmissions;
		protected TextBox _actualOuPatientVisits;
		protected TextBox _actualScatterNurseVisits;
		protected TextBox _actualAdmissionAncillaries;
		protected TextBox _totalChargesAdmissionAncillaries;
		protected TextBox _totalNetChargesAdmissionAncillaries;
		protected TextBox _actualOutPatientAncillaries;
		protected TextBox _totalChargesOutPatientAncillaries;
		protected TextBox _totalNetChargesOutPatientAncillaries;
		protected DataGrid _dgPatients;
		protected DataGrid _dgAdmissions;
		protected DataGrid _dgOutVisits;
		protected DataGrid _dgScatterNurse;
		protected DataGrid _dgAdmissionAncillaries;
		protected DataGrid _dgOutPatientAncillaries;
		protected TabControlAdv _tab2;
		protected Syncfusion.Windows.Forms.Tools.DateTimePickerAdv _irbApproval;
		protected Syncfusion.Windows.Forms.Tools.DateTimePickerAdv _irbRenewal;
		protected TextBox _irbCalcExpire;
		protected TextBox _score;
		//defaults
		protected ComboBox _pSite;
		protected ComboBox _pCategory;

		protected ComboBox _medicalRecords;
		protected ComboBox _consentToMR;
		protected ComboBox _nurseBinder;
		protected ComboBox _phase;
		protected ComboBox _previousPI;
		
		#endregion control references

		#region initialize
		public BLFormProtocolImpl(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{

		}
		protected override void _vcManager_OnAfterHookEvents()
		{
			base._vcManager_OnAfterHookEvents();
			_protocolStaff = (UserGrid)Forms.Utils.GetControlByName("ProtocolStaff", this._form.Controls);
			_incomplete = (CheckBox)Forms.Utils.GetControlByName("Incomplete", this._form.Controls);
			_active = (CheckBox)Forms.Utils.GetControlByName("Active", this._form.Controls);
			_btnAddInvetig = (Button)Forms.Utils.GetControlByName("btnAddInvetig", this._form.Controls);
			_id = (TextBox)Forms.Utils.GetControlByName("ID", this._form.Controls);
			_actualPatients = (TextBox)Forms.Utils.GetControlByName("ActualPatients", this._form.Controls);
			_actualAdmissions = (TextBox)Forms.Utils.GetControlByName("ActualAdmissions", this._form.Controls);
			_actualOuPatientVisits = (TextBox)Forms.Utils.GetControlByName("ActualOuPatientVisits", this._form.Controls);
			_actualScatterNurseVisits = (TextBox)Forms.Utils.GetControlByName("ActualScatterNurseVisits", this._form.Controls);
			_actualAdmissionAncillaries = (TextBox)Forms.Utils.GetControlByName("ActualAdmissionAncillaries", this._form.Controls);
			_totalChargesAdmissionAncillaries = (TextBox)Forms.Utils.GetControlByName("TotalChargesAdmissionAncillaries", this._form.Controls);
			_totalNetChargesAdmissionAncillaries = (TextBox)Forms.Utils.GetControlByName("TotalNetChargesAdmissionAncillaries", this._form.Controls);
			_actualOutPatientAncillaries = (TextBox)Forms.Utils.GetControlByName("ActualOutPatientAncillaries", this._form.Controls);
			_totalChargesOutPatientAncillaries = (TextBox)Forms.Utils.GetControlByName("TotalChargesOutPatientAncillaries", this._form.Controls);
			_totalNetChargesOutPatientAncillaries = (TextBox)Forms.Utils.GetControlByName("TotalNetChargesOutPatientAncillaries", this._form.Controls);
			_score = (TextBox)Forms.Utils.GetControlByName("Score", this._form.Controls);
			_score.KeyPress += new KeyPressEventHandler(Forms.Utils.txtNumDecPos_KeyPress);
			_dgPatients = (DataGrid)Forms.Utils.GetControlByName("dgPatients", this._form.Controls);
			_dgAdmissions = (DataGrid)Forms.Utils.GetControlByName("dgAdmissions", this._form.Controls);
			_dgOutVisits = (DataGrid)Forms.Utils.GetControlByName("dgOutVisits", this._form.Controls);
			_dgScatterNurse = (DataGrid)Forms.Utils.GetControlByName("dgScatterNurse", this._form.Controls);
			_dgAdmissionAncillaries = (DataGrid)Forms.Utils.GetControlByName("dgAdmissionAncillaries", this._form.Controls);
			_dgOutPatientAncillaries = (DataGrid)Forms.Utils.GetControlByName("dgOutPatientAncillaries", this._form.Controls);
			_tab2 = (TabControlAdv)Forms.Utils.GetControlByName("tab2", this._form.Controls);

			_irbApproval = (DateTimePickerAdv)Forms.Utils.GetControlByName("IrbApproval", this._form.Controls);
			_irbRenewal = (DateTimePickerAdv)Forms.Utils.GetControlByName("IrbRenewal", this._form.Controls);
			_irbCalcExpire = (TextBox)Forms.Utils.GetControlByName("IrbCalcExpire", this._form.Controls);
			
			_pSite = (ComboBox)Forms.Utils.GetControlByName("PSite", this._form.Controls);
			_pCategory = (ComboBox)Forms.Utils.GetControlByName("PCategory", this._form.Controls);

			_pSite.SelectedIndexChanged += new EventHandler(_default_SelectedIndexChanged);
			_pCategory.SelectedIndexChanged += new EventHandler(_default_SelectedIndexChanged);

			_medicalRecords = (ComboBox)Forms.Utils.GetControlByName("MedicalRecords", this._form.Controls);
			_consentToMR = (ComboBox)Forms.Utils.GetControlByName("ConsentToMR", this._form.Controls);
			_nurseBinder = (ComboBox)Forms.Utils.GetControlByName("NurseBinder", this._form.Controls);
			_phase = (ComboBox)Forms.Utils.GetControlByName("Phase", this._form.Controls);
			_previousPI = (ComboBox)Forms.Utils.GetControlByName("PreviousPI", this._form.Controls);
			
			_protocolStaff.Grid.CurrentCellValidating += new CancelEventHandler(grdStaff_CurrentCellValidating);
			this._irbApproval.ValueChanged += new EventHandler(Approval_Renewal_ValueChanged);
			this._irbRenewal.ValueChanged += new EventHandler(Approval_Renewal_ValueChanged);
			this._incomplete.Click += new EventHandler(_incomplete_Click);
		}
                
        void grdStaff_CurrentCellValidating(object sender, CancelEventArgs e)
        {
            try
            {
                //BLFormGridBaseImpl fgbl = (BLFormGridBaseImpl)_gridBLs["ProtocolStaff"];
                GridControl grd = _protocolStaff.Grid;
                GridCurrentCell cc = grd.CurrentCell;
                int val = int.Parse(cc.Renderer.ControlValue.ToString());
                //bool isPrincipalUsed = false;

                for (int i = 1; i < grd.RowCount + 1; i++)
                {
					if (i == cc.RowIndex)
						continue;
					//investigators
					if (cc.ColIndex == 2)
					{						
						if (((int)grd[i, 2].CellValue) == val)
						{
							MessageBox.Show(this._form, "Duplicate investigators are not allowed");
							e.Cancel = true;
						}
					}

                    //
                    if (cc.ColIndex == 3)
                    {
                        if (val == 1)
                        {
                            if (((int)grd[i, 3].CellValue) == 1)
                            {
                                MessageBox.Show(this._form, "More than one principal investigator is not allowed");
                                e.Cancel = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //temporary fix for cell value being null
            }
            
        }

		private void _default_SelectedIndexChanged(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			ComboBox cbo = (ComboBox)sender;
			string field = cbo.Name;

			if (this._formMode != EditMode.Edit)
				return;

			if (!_isExistsVisits)
				return;

			int newVal = (int)cbo.SelectedValue;

			int num = 0;
			bool isVisitApplicable = false;
			//see if the change pertains to the existing visits
			switch (field)
			{
				case "PCategory":
					isVisitApplicable = true;
					break;
				case "PSite":
					if (_actualAdmissions.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualAdmissions.Text);
						if (num > 0)
							isVisitApplicable = true;
						break;
					}
					if (_actualOuPatientVisits.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualOuPatientVisits.Text);
						if (num > 0)
							isVisitApplicable = true;
					}
					break;
			}

			if (!isVisitApplicable)
				return;

			ProtocolDefaultChangeDlg dlg = new ProtocolDefaultChangeDlg();
			dlg.ShowDialog(this._form);
			ProtocolDefaultChangeResult rslt = dlg.DefaultChangeDialogResult;
			Console.WriteLine("Result: " + rslt.ToString());

			switch (rslt)
			{
				case ProtocolDefaultChangeResult.NoChange:
					return;
				case ProtocolDefaultChangeResult.ChangeAll:
					ChangeAllVisits(newVal, field);
					break;
				case ProtocolDefaultChangeResult.Prompt:
					PromptVisitChange(newVal, field);
					break;
			}
		}

		private void PromptVisitChange(int newVal, string field)
		{
			int num = 0;
			switch (field)
			{
				case "PCategory":
					if (_actualAdmissions.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualAdmissions.Text);
						if (num > 0)
							DisplayVisitChangePrompt("ProtocolVisitAdmission", newVal, field);
					}
					if (_actualOuPatientVisits.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualOuPatientVisits.Text);
						if (num > 0)
							DisplayVisitChangePrompt("ProtocolVisitOutPatient", newVal, field);
					}
					if (_actualScatterNurseVisits.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualScatterNurseVisits.Text);
						if (num > 0)
							DisplayVisitChangePrompt("ScatterNurseHours", newVal, field);
					}
					break;
				case "PSite":
					if (_actualAdmissions.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualAdmissions.Text);
						if (num > 0)
							DisplayVisitChangePrompt("ProtocolVisitAdmission", newVal, field);
					}
					if (_actualOuPatientVisits.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualOuPatientVisits.Text);
						if (num > 0)
							DisplayVisitChangePrompt("ProtocolVisitOutPatient", newVal, field);
					}
					break;
			}

		}

		private void DisplayVisitChangePrompt(string table, int newVal, string field)
		{
			int id = Convert.ToInt32(this._id.Text);
			VisitChangePromptDlg dlg = new VisitChangePromptDlg(table, id, newVal, field);
			if (dlg.InitializeGrid())
				dlg.ShowDialog(this._form);

		}

		private void ChangeAllVisits(int newVal, string field)
		{
			int num;
			switch (field)
			{
				case "PCategory":
					if (_actualAdmissions.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualAdmissions.Text);
						if (num > 0)
							UpdateAllVisits("ProtocolVisitAdmission", newVal, field);
					}
					if (_actualOuPatientVisits.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualOuPatientVisits.Text);
						if (num > 0)
							UpdateAllVisits("ProtocolVisitOutPatient", newVal, field);
					}
					if (_actualScatterNurseVisits.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualScatterNurseVisits.Text);
						if (num > 0)
							UpdateAllVisits("ScatterNurseHours", newVal, field);
					}
					break;
				case "PSite":
					if (_actualAdmissions.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualAdmissions.Text);
						if (num > 0)
							UpdateAllVisits("ProtocolVisitAdmission", newVal, field);
					}
					if (_actualOuPatientVisits.Text.Length > 0)
					{
						num = Convert.ToInt32(_actualOuPatientVisits.Text);
						if (num > 0)
							UpdateAllVisits("ProtocolVisitOutPatient", newVal, field);
					}
					break;
			}
		}

		private void UpdateAllVisits(string table, int newVal, string field)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "UPDATE " + table + " SET " + field +
				"=" + newVal +
				" WHERE Protocol=" + this._id.Text;

			int result = 0;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				result = DataAccess.ExecuteNonQuery(CommandType.Text, sql);
			}
			catch (Exception ex)
			{
				sb.Append("Could not update visits!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Update All Visist Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
			sb.Append("Updated " + result + " records.");
			MessageBox.Show(this._form, sb.ToString(), "Update All Visists", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

		private void Approval_Renewal_ValueChanged(object sender, EventArgs e)
		{
			CalculateIrbExpiration();
		}

		private void CalculateActive()
		{
			_active.Checked = false;
			if (this._irbCalcExpire.Text.Length == 0)
				return;
			DateTime dtExp = Convert.ToDateTime(_irbCalcExpire.Text);
			if (DateTime.Today.CompareTo(dtExp) < 1)
				_active.Checked = true;
		}

		private void CalculateIrbExpiration()
		{
			DateTime dtApp;
			DateTime dtRen;
			DateTime dtLatest;

			if (this._irbApproval.IsNullDate && this._irbRenewal.IsNullDate)
			{
				_irbCalcExpire.Text = "";
				return;
			}

			if (this._irbApproval.IsNullDate || this._irbRenewal.IsNullDate)
			{
				if (this._irbApproval.IsNullDate)
					dtLatest = this._irbRenewal.Value;
				else
					dtLatest = this._irbApproval.Value;
			}
			else
			{
				dtApp = this._irbApproval.Value;
				dtRen = this._irbRenewal.Value;
				dtLatest = dtApp;

				if (dtRen.CompareTo(dtApp) > 0)
					dtLatest = dtRen;
			}

			int year = dtLatest.Year;
			int mon = dtLatest.Month;
			int day = dtLatest.Day;
			int addDays = 364;

			if (DateTime.IsLeapYear(year))
			{
				if (mon < 3)
				{
					addDays = 365;

					//					if(mon == 2)
					//					{
					//						if(day == 29)
					//							addDays = 364;
					//					}					
				}
			}
			if (DateTime.IsLeapYear(year + 1))
			{
				if (mon > 2)
				{
					addDays = 365;
				}
			}

			this._irbCalcExpire.Text = dtLatest.AddDays(addDays).ToShortDateString();
		}
		#endregion initialize

		#region search
		public override void Search(object sender)
		{
			Control ctl = (Control)sender;

			ctl.Enabled = false;

			SelectProtocolDlg spd = new SelectProtocolDlg();
			spd.ShowDialog(this._form);
			if (spd.SearchChoice == 0)
				SelectProtocolStandard();
			else if (spd.SearchChoice == 1)
				SelectProtocolByInvestigator();
			else if (spd.SearchChoice == 2)
				SelectByPreviousNumber();
			else if (spd.SearchChoice == 3)
				SelectByPreviousPI();

			ctl.Enabled = true;
		}

		private void SelectByPreviousPI()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["PreviousPI"];
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Owner = this._form;
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol previous number seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectByPreviousNumber()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["ProtocolPreviousNumber"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Owner = this._form;
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol previous number seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectProtocolByInvestigator()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Investigator"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Owner = this._form;
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectProtocolStandard()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Protocol"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Owner = this._form;
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void sc_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				Console.WriteLine("Selected ID: " + e.ID.ToString());
				if (GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
		}

		private void fs_Closing(object sender, CancelEventArgs e)
		{
			IsSearchVisible = false;
			this._form.btnSearch.Enabled = true;
		}

		#endregion search

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);
			_btnAddInvetig.Enabled = enable;
			this._irbCalcExpire.Enabled = enable;

			
		}

		//public override void New()
		//{
		//    //commented out form lock and unlock
		//    StringBuilder sb = new StringBuilder();
		//    //SqlConnection conn = LoginForm.GetSqlConnection();
		//    try
		//    {
		//        //See if the form is locked			
		//        if ((bool)DataAccess.GetScalarObject(CommandType.Text, "SELECT IsLocked FROM FormLock WHERE FormID=24"))
		//        {
		//            sb.Append("The protocol table is locked.  Someone else is adding a new protocol.");
		//            sb.Append(Environment.NewLine);
		//            sb.Append("Try again after they have saved the new protocol.");
		//            sb.Append(Environment.NewLine);
		//            MessageBox.Show(this._form, sb.ToString(), "Table Lock", MessageBoxButtons.OK, MessageBoxIcon.Stop);
		//            return;
		//        }

		//        //lock the protocol 
		//        if (DataAccess.ExecuteNonQuery(CommandType.Text, "UPDATE FormLock SET IsLocked = 1 WHERE FormID=24") != 1)
		//        {
		//            sb.Append("Could not lock protocol form.");
		//            sb.Append(Environment.NewLine);
		//            sb.Append(Shared.Constants.NotifySupportImmediate);
		//            MessageBox.Show(this._form, sb.ToString(), "Table Lock", MessageBoxButtons.OK, MessageBoxIcon.Stop);
		//            return;
		//        }

		//        //get the last spid number and increment it
		//        //int spid = 0;
		//        //object o = DataAccess.GetScalarObject(CommandType.Text, "SELECT MAX(SPID) FROM Protocol");
		//        //if (o.ToString().Length > 0)
		//        //    spid = (int)o;

		//        //spid++;
		//        base.New();
		//        //FieldContext fc = (FieldContext)this.FieldContextManager.Item("SPID");
		//        //fc.Control.Text = spid.ToString("0000");


		//    }
		//    catch (Exception ex)
		//    {
		//        //bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
		//        sb.Append("New data table could not be created");
		//        sb.Append(Environment.NewLine);
		//        sb.Append("Error message: " + ex.Message);
		//        MessageBox.Show(this._form, sb.ToString(), "New Data Table Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
		//        return;
		//    }
		//    finally
		//    {
		//        //if(conn != null)
		//        //    conn.Dispose();	
		//    }
		//}

        public override bool Remove()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Press 'Yes' to confirm the removal of Protocol ID: " + this._currentPrimaryID.ToString() + ".");
            sb.Append(Environment.NewLine);
            sb.Append("Note: this will also remove all visits and ancillaries related to this protocol.");
            sb.Append(Environment.NewLine);
            sb.Append("or press 'No' to cancel.");
            if (MessageBox.Show(this._form, sb.ToString(), "Confirm Protocol Removal", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                return false;

            sb.Remove(0, sb.Length);

			//this is used as a parameter for table grid display
			DbTableChange tableChange = DbTableChange.Update;

			string sql = "DELETE FROM Protocol WHERE ID=" + this._currentPrimaryID;
            			
			try
			{				
            
                int i = DataAccess.ExecuteNonQuery(CommandType.Text, sql);
                if (i == 1)
                {
                    sb.Append("Protocol ID: " + this._currentPrimaryID.ToString() + " was deleted.");
                    this._fcManager.CurrentRow.Delete();
                    this.ResetToOriginal();
                    MessageBox.Show(this._form, sb.ToString(), "Confirm Protocol Removal", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    BLTableChangeAdvEventArgs args = new BLTableChangeAdvEventArgs(this._formInfo.TableName, tableChange, this._currentPrimaryID - 1);

                    this.FireTableChange(args);
                }
                else
                {
                    sb.Append("Protocol ID: " + this._currentPrimaryID.ToString() + " was not deleted.");
                    sb.Append(Environment.NewLine);
                    sb.Append(Shared.Constants.NotifySupportImmediate);
                    MessageBox.Show(this._form, sb.ToString(), "Confirm Protocol Removal", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return true;
            }
            catch (Exception ex)
            {
                sb.Append("Could not delete protocol!");
                sb.Append(Environment.NewLine);
                sb.Append("Error message: " + ex.Message);
               
                MessageBox.Show(this._form, sb.ToString(), "Delete Ancillary Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            
        }

        public override bool Save()
		{
			StringBuilder sb = new StringBuilder();
			string message = "";

			//this is used as a parameter for table grid display
			//DbTableChange tableChange = DbTableChange.Update;

			if (this._doSummaryValidate)
			{
				if (!VerifyAll())
					return false;
				if (!VerifyGrids())
					return false;
			}

			Console.WriteLine("RowState brfore save: " + this._fcManager.CurrentRow.RowState.ToString());

			Database db = DatabaseFactory.CreateDatabase();
			using (DbConnection conn = db.CreateConnection())
			{
				try
				{
					conn.Open();
					DbTransaction trans = conn.BeginTransaction();
					if (_formMode == EditMode.New)
					{
						//tableChange = DbTableChange.Insert;
						if (!SaveNew(out message, db, trans))
						{
							trans.Rollback();
							sb.Append("New record for " + this._formInfo.Name + " could not be saved.");
							sb.Append(Environment.NewLine);
							sb.Append("Error: " + message);
							MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return false;
						}

					}
					else if (_formMode == EditMode.Edit)
					{
						if (!Update(out message, db, trans))
						{
							trans.Rollback();
							sb.Append("Update for " + this._formInfo.Name + " could not be saved.");
							sb.Append(Environment.NewLine);
							sb.Append("Error: " + message);
							MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return false;
						}
					}

					if (this._gridBLs != null)
					{
						if (!SaveGrids(out message, db, trans))
						{
							trans.Rollback();
							sb.Append("Grid data " + this._formInfo.Name + " could not be saved.");
							sb.Append(Environment.NewLine);
							sb.Append("Error: " + message);
							MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return false;
						}
					}

					trans.Commit();
					//confirmation dialog
					MessageBox.Show("Record was saved.", "Save Confirmation",
						MessageBoxButtons.OK, MessageBoxIcon.Information);

					bool shouldClose = (bool)this._configData["CloseOnSave"];
					if (shouldClose)
					{
						this._isClosing = true;
						this._form.Close();
					}
					else
					{
						//commented out form lock and unlock
						//if (this.FieldContextManager.CurrentRow.RowState == DataRowState.Added)
						//{
						//    try
						//    {
						//        DataAccess.ExecuteNonQuery(CommandType.Text, "UPDATE FormLock SET IsLocked = 0 WHERE FormID=24");
						//    }
						//    catch (Exception ex)
						//    {
						//        //bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
						//        sb.Append("Could not unlock protocl.");
						//        sb.Append(Environment.NewLine);
						//        sb.Append("Error message: " + ex.Message);
						//        MessageBox.Show(this._form, sb.ToString(), "Unlock Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
						//    }
						//}
						this._fcManager.CurrentRow.AcceptChanges();
						SetGridsAcceptChanges();
						SetFormMode(EditMode.Read);
					}

					this.FireTableChange(DbTableChange.Update);
					Console.WriteLine("RowState after save: " + this._fcManager.CurrentRow.RowState.ToString());
					return true;
				}
				catch (Exception ex)
				{
					//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
					sb.Append("Batch could not be saved.");
					sb.Append(Environment.NewLine);
					sb.Append("Error message: " + ex.Message);
					MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}
				finally
				{
					if (conn != null)
						conn.Dispose();
				}
			}
		}

		protected override bool VerifyGrids()
		{
			ProtocolGridValidationErrorType errType = Shared.ProtocolGridValidationErrorType.none;
			StringBuilder sb = new StringBuilder();
			string message = "";

			if (this._gridBLs != null)
			{
				foreach (BLFormGridBaseImpl fgbl in this._gridBLs.Values)
				{
					if (!fgbl.VerifyGrid(out message, out errType))
					{
						if (errType == ProtocolGridValidationErrorType.fieldRequired)
						{
							sb.Append("Protocol could not be saved.");
							sb.Append(Environment.NewLine);
							sb.Append(message);
							MessageBox.Show(this._form, sb.ToString(), "Data Validation Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
							return false;
						}
						else
						{
							this._incomplete.Checked = true;
							sb.Append("Protocol will be saved as incomplete:");
							sb.Append(Environment.NewLine);
							sb.Append(message);
							MessageBox.Show(this._form, sb.ToString(), "Data Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
							this._incomplete.Checked = true;
						}
					}
				}
			}
			return true;
		}

		protected override bool VerifyAll()
		{
			StringBuilder sb = new StringBuilder();
			MethodInfo mi = null;
			Object[] args = new Control[1];

			//this tells GetMethod what type of methods to look for
			BindingFlags bf = BindingFlags.NonPublic | BindingFlags.Instance;//| BindingFlags.DeclaredOnly; 

			//initialize this to false and let the validation set it to true
			this._incomplete.Checked = false;
			foreach (FieldContext fc in this._fcManager.Items)
			{
				if (fc.Control == null)
					continue;
				if (fc.VerifyName.Length == 0)
					continue;

				args[0] = fc.Control;
				mi = this.GetType().GetMethod(fc.VerifyName, bf);
				if (mi == null)
				{
					sb.Append("Could not save form:");
					sb.Append(Environment.NewLine);
					if (fc.Labels == null)
						sb.Append("Field: " + fc.Column.ColumnName);
					else
						sb.Append("Field: " + fc.Labels.Label);
					sb.Append(Environment.NewLine);
					sb.Append("The VerifyName: " + fc.VerifyName + " was not found.");
					sb.Append(Environment.NewLine);
					sb.Append(Constants.NotifySupportImmediate);
					Exception ex = new Exception(sb.ToString());
					//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
					MessageBox.Show(this._form, sb.ToString(), "Data Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
					return false;
				}
				if (!(bool)mi.Invoke(this, args))
				{
					//Microsoft.VisualBasic.Interaction.Beep();
					if (fc.Column.ColumnName == "ProtocolNumber")
						sb.Append("Protocol could not be saved.");
					else
					{
						if (fc.IsIncomplete)
							sb.Append("Protocol will be saved as incomplete:");
					}

					sb.Append(Environment.NewLine);
					if (fc.Labels == null)
						sb.Append("Field: " + fc.Column.ColumnName);
					else
						sb.Append("Field: " + fc.Labels.Label);
					sb.Append(Environment.NewLine);

					sb.Append("Message: " + fc.ErrorMessage);

					if (fc.Column.ColumnName == "ProtocolNumber" || fc.IsIncomplete == false)
					{
                        MessageBox.Show(this._form, sb.ToString(), "Data Validation Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
						fc.Control.Focus();
						return false;
					}

					if (fc.IsIncomplete)
					{
						MessageBox.Show(this._form, sb.ToString(), "Data Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
						this._incomplete.Checked = true;
					}
				}
			}

			return true;
		}

		protected virtual bool VerifyScore(Control ctl)
		{
			bool retVal = true;
			FieldContext fc = (FieldContext)ctl.Tag;

			Console.WriteLine("VerifyText,Control: " + ctl.Name);

			if (fc.Manager.CurrentRow == null)
				return true;

			Console.WriteLine("CurrentValue: " + fc.CurrentValue.ToString());

			if (ctsu.Admin.Forms.Utils.IsMissingValue(ctl))
			{
				//todo - might have to grandfather prior to ctsa 
				return true;
			}

			decimal min = new decimal(1.0);
			decimal max = new decimal(5.0);
			//range
			try
			{
				decimal dec = decimal.Parse(ctl.Text);
				if ((dec.CompareTo(min) < 0) || (dec.CompareTo(max) > 0))
				{
					fc.IsIncomplete = false;
					fc.ErrorMessage = "Invalid value - must be within range: 1.0 to 5.0";
					return false;

				}
			}
			catch
			{
				fc.IsIncomplete = false;
				fc.ErrorMessage = "Invalid value - must be within range: 1.0 to 5.0";
				return false;
			}

			Console.WriteLine("Column Changed = " + fc.IsColumnChanged(fc.Column.ColumnName).ToString());

			Console.WriteLine("ErrorMessage: " + fc.ErrorMessage);
			Console.WriteLine("Return Value: " + retVal.ToString());

			return retVal;
		}

		public override void Cancel()
		{
			StringBuilder sb = new StringBuilder();
			bool confirmCancel = false;

			if (_form.btnSave.Enabled)
			{
				if (MessageBox.Show(_form, "Do you want to cancel without saving changes?", "Confirm Cancel",
					MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					confirmCancel = true;
				}
			}
			else
				//don't need confirm
				confirmCancel = true;

			if (!confirmCancel)
				return;

			//commented out form lock and unlock
			//SqlConnection conn = LoginForm.GetSqlConnection();
			//if (this.FieldContextManager.CurrentRow.RowState == DataRowState.Added)
			//{
			//    try
			//    {
			//        DataAccess.ExecuteNonQuery(CommandType.Text, "UPDATE FormLock SET IsLocked = 0 WHERE FormID=24");
			//    }
			//    catch (Exception ex)
			//    {
			//        //bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
			//        sb.Append("Could not unlock protocl.");
			//        sb.Append(Environment.NewLine);
			//        sb.Append("Error message: " + ex.Message);
			//        MessageBox.Show(this._form, sb.ToString(), "Unlock Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			//    }
			//    finally
			//    {
			//        //if(conn != null)
			//        //conn.Dispose();
			//    }
			//}

			//check config setting
			bool shouldClose = (bool)this._configData["CloseOnCancel"];
			if (shouldClose)
			{
				this._isClosing = true;
				this._form.Close();
			}
			else
			{
				//reset data to original vlaues				
				ResetToOriginal();
				ResetGrids();
			}
		}

		//commented out form lock and unlock
		//public override bool Closing()
		//{
		//    StringBuilder sb = new StringBuilder();
		//    if (base.Closing())
		//        return true;  //closing was cancelled

		//    //SqlConnection conn = LoginForm.GetSqlConnection();
		//    if (this.FieldContextManager.CurrentRow != null)
		//    {
		//        if (this.FieldContextManager.CurrentRow.RowState == DataRowState.Added)
		//        {
		//            try
		//            {
		//                DataAccess.ExecuteNonQuery(CommandType.Text, "UPDATE FormLock SET IsLocked = 0 WHERE FormID=24");
		//            }
		//            catch (Exception ex)
		//            {
		//                //bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
		//                sb.Append("Could not unlock protocl.");
		//                sb.Append(Environment.NewLine);
		//                sb.Append("Error message: " + ex.Message);
		//                MessageBox.Show(this._form, sb.ToString(), "Unlock Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
		//            }
		//            finally
		//            {
		//                //if(conn != null)
		//                //    conn.Dispose();
		//            }
		//        }
		//    }
		//    return false;
		//}

		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnAddInvetig")
				DisplayNewInvestigForm();
			//			if(sender.Name == "btnGetActual")
			//				DisplayActualNumbers();
			if (sender.Name == "btnViewPatients")
				DisplayPatients();
			if (sender.Name == "btnViewAdmissions")
				DisplayAdmissions();
			if (sender.Name == "btnViewOutVisits")
				DisplayOutPatientVisits();
			if (sender.Name == "btnViewScatter")
				DisplayScatterNurseVisits();
			if (sender.Name == "btnViewAdmissionAncillary")
				DisplayAdmissionAncillaries();
			if (sender.Name == "btnViewOutPatientAncillary")
				DisplayOutPatientAncillaries();
			if (sender.Name == "btnCalcAdmissionAncillaryGross")
				CalcAdmissionAncillaryGross();
			if (sender.Name == "btnCalcAdmissionAncillaryNet")
				CalcAdmissionAncillaryNet();
			if (sender.Name == "btnCalcOutpatientAncillaryGross")
				CalcOutpatientAncillaryGross();
			if (sender.Name == "btnCalcOutpatientAncillaryNet")
				CalcOutpatientAncillaryNet();
			if (sender.Name == "btnPrintGrid")
				PrintGridActual(sender);
		}

		private void CalcOutpatientAncillaryNet()
		{
			decimal charge = this.GetActualOutPatientAncillariesNetCharges(this._currentPrimaryID);
			this._totalNetChargesOutPatientAncillaries.Text = charge.ToString("c");
		}

		private void CalcOutpatientAncillaryGross()
		{
			decimal charge = this.GetActualOutPatientAncillariesGrossCharge(this._currentPrimaryID);
			this._totalChargesOutPatientAncillaries.Text = charge.ToString("c");
		}

		private void CalcAdmissionAncillaryNet()
		{
			decimal charge = this.GetActualAdmissionAncillariesNetCharges(this._currentPrimaryID);
			this._totalNetChargesAdmissionAncillaries.Text = charge.ToString("c");
		}

		private void CalcAdmissionAncillaryGross()
		{
			decimal charge = this.GetActualAdmissionAncillariesGrossCharge(this._currentPrimaryID);
			this._totalChargesAdmissionAncillaries.Text = charge.ToString("c");
		}

		private void DisplayScatterNurseVisits()
		{
			StringBuilder sb = new StringBuilder();
			int protoID = Convert.ToInt32(this._id.Text);
			string sql = "SELECT a.ID,a.VisitDate,a.Duration,n.Display,c.Display AS Category, " +
				" p.LastName+', '+p.FirstName AS Patient " +
				" FROM ScatterNurseHours a,PCategory_L c,Nurse_L n,Patient p " +
				" WHERE Protocol=" + protoID +
				" AND a.Nurse=n.ID " +
				" AND a.Pcategory=c.ID " +
				" AND a.Patient=p.ID " +
				" ORDER BY a.VisitDate"; ;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				DataColumn dc = dt.Columns["ID"];
				dc.Caption = "ID";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["VisitDate"];
				dc.Caption = "Admit Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Duration"];
				dc.Caption = "Duration";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Category"];
				dc.Caption = "Category";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Patient"];
				dc.Caption = "Patient";
				dc.ExtendedProperties.Add("Width", 150);

				_dgScatterNurse.DataSource = dt;
				_tab2.SelectedIndex = 3;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display nurse visits.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}

		}

		private void DisplayOutPatientVisits()
		{
			StringBuilder sb = new StringBuilder();
			int protoID = Convert.ToInt32(this._id.Text);
			string sql = "SELECT a.ID,a.VisitDate,a.Duration,c.Display AS Category, " +
				" p.LastName+', '+p.FirstName AS Patient " +
				" FROM ProtocolVisitOutPatient a,PCategory_L c,Patient p " +
				" WHERE Protocol=" + protoID +
				" AND a.Pcategory=c.ID " +
				" AND a.Patient=p.ID " +
				" ORDER BY a.VisitDate";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				DataColumn dc = dt.Columns["ID"];
				dc.Caption = "ID";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["VisitDate"];
				dc.Caption = "Admit Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Duration"];
				dc.Caption = "Duration";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Category"];
				dc.Caption = "Category";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Patient"];
				dc.Caption = "Patient";
				dc.ExtendedProperties.Add("Width", 150);


				_dgOutVisits.DataSource = dt;
				_tab2.SelectedIndex = 2;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display out patient visits.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void DisplayAdmissions()
		{
			StringBuilder sb = new StringBuilder();
			int protoID = Convert.ToInt32(this._id.Text);
			string sql = "SELECT a.ID,a.VisitDate,a.DischargeDate,c.Display AS Category, " +
				" p.LastName+', '+p.FirstName AS Patient " +
				" FROM ProtocolVisitAdmission a,PCategory_L c,Patient p " +
				" WHERE Protocol=" + protoID +
				" AND a.Pcategory=c.ID " +
				" AND a.Patient=p.ID " +
				" ORDER BY a.VisitDate";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				DataColumn dc = dt.Columns["ID"];
				dc.Caption = "ID";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["VisitDate"];
				dc.Caption = "Admit Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["DischargeDate"];
				dc.Caption = "Discharge Date";
				dc.ExtendedProperties.Add("Width", 120);

				dc = dt.Columns["Category"];
				dc.Caption = "Category";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Patient"];
				dc.Caption = "Patient";
				dc.ExtendedProperties.Add("Width", 150);

				_dgAdmissions.DataSource = dt;
				_tab2.SelectedIndex = 1;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display admissions.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void DisplayAdmissionAncillaries()
		{
			StringBuilder sb = new StringBuilder();
			int protoID = Convert.ToInt32(this._id.Text);
			string sql = "SELECT a.ID,a.TestDate,a.Visit AS [Visit ID], " +
				" a.Charge, STR(((SELECT Rate FROM AncillaryRate " +
				" WHERE CostCenter = a.CostCenter " +
				" AND StartDate <= a.TestDate AND EndDate >= a.TestDate)*a.Charge),9,2) AS Net, " +
				" c.Display AS [Cost Center] " +
				" FROM ProtocolVisitAdmission p, AncillaryAdmission a,CostCenter c " +
				" WHERE p.Protocol=" + protoID +
				" AND a.CostCenter=c.ID " +
				" AND p.ID=a.Visit " +
				" ORDER BY a.TestDate";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				DataColumn dc = dt.Columns["ID"];
				dc.Caption = "ID";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["TestDate"];
				dc.Caption = "Test Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Visit ID"];
				dc.Caption = "Visit ID";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Charge"];
				dc.Caption = "Charge";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Net"];
				dc.Caption = "Net";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Cost Center"];
				dc.Caption = "Cost Center";
				dc.ExtendedProperties.Add("Width", 300);

				_dgAdmissionAncillaries.DataSource = dt;
				_tab2.SelectedIndex = 4;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display out admission ancillaries.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void DisplayOutPatientAncillaries()
		{
			StringBuilder sb = new StringBuilder();
			int protoID = Convert.ToInt32(this._id.Text);
			string sql = "SELECT a.ID,a.TestDate,a.Visit AS [Visit ID], " +
				" a.Charge, STR(((SELECT Rate FROM AncillaryRate " +
				" WHERE CostCenter = a.CostCenter " +
				" AND StartDate <= a.TestDate AND EndDate >= a.TestDate)*a.Charge),9,2) AS Net, " +
				" c.Display AS [Cost Center] " +
				" FROM ProtocolVisitOutPatient p, AncillaryOutPatient a,CostCenter c " +
				" WHERE p.Protocol=" + protoID +
				" AND a.CostCenter=c.ID " +
				" AND p.ID=a.Visit " +
				" ORDER BY a.TestDate";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				DataColumn dc = dt.Columns["ID"];
				dc.Caption = "ID";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["TestDate"];
				dc.Caption = "Test Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Visit ID"];
				dc.Caption = "Visit ID";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Charge"];
				dc.Caption = "Charge";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Net"];
				dc.Caption = "Net";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Cost Center"];
				dc.Caption = "Cost Center";
				dc.ExtendedProperties.Add("Width", 300);

				_dgOutPatientAncillaries.DataSource = dt;
				_tab2.SelectedIndex = 5;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display out out patient ancillaries.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void DisplayPatients()
		{
			StringBuilder sb = new StringBuilder();
			int protoID = Convert.ToInt32(this._id.Text);
			string sql = "SELECT Patient INTO ##TPat FROM ProtocolVisitAdmission " +
				" WHERE Protocol=" + protoID;

			Database db = DatabaseFactory.CreateDatabase();
			DbConnection conn = db.CreateConnection();
			DbCommand cmd = db.GetSqlStringCommand(sql);
			cmd.Connection = conn;
			try
			{
				//the connection must be open in order to work with the same temp table				
				cmd.Connection.Open();
				cmd.CommandType = CommandType.Text;
				cmd.ExecuteNonQuery();

				sql = "INSERT INTO ##TPat " +
					"SELECT Patient FROM ProtocolVisitOutPatient " +
					" WHERE Protocol=" + protoID;
				cmd.CommandText = sql;
				cmd.ExecuteNonQuery();

				sql = "INSERT INTO ##TPat " +
					"SELECT Patient FROM ScatterNurseHours " +
					" WHERE Protocol=" + protoID;
				cmd.CommandText = sql;
				cmd.ExecuteNonQuery();

				sql = "SELECT DISTINCT ID, MRN, OtherPatientID AS [Other ID], LastName+', '+FirstName AS Name " +
					" FROM Patient p, ##TPat t" +
					" WHERE p.ID=t.Patient " +
					" ORDER BY Name";

				DbDataAdapter da = db.GetDataAdapter();
				cmd.CommandText = sql;
				da.SelectCommand = cmd;

				//SqlDataAdapter da = new SqlDataAdapter(sql, );
				DataTable dt = new DataTable();
				da.Fill(dt);

				DataColumn dc = dt.Columns["ID"];
				dc.Caption = "ID";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["MRN"];
				dc.Caption = "MRN";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Other ID"];
				dc.Caption = "Other ID";
				dc.ExtendedProperties.Add("Width", 120);

				dc = dt.Columns["Name"];
				dc.Caption = "Patient Name";
				dc.ExtendedProperties.Add("Width", 150);

				_dgPatients.DataSource = dt;
				_tab2.SelectedIndex = 0;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Form could display patients.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Display Patients Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				if (cmd.Connection.State == ConnectionState.Open)
					cmd.Connection.Close();
			}
		}

		public override void DisplayData()
		{
			base.DisplayData();
			CalculateIrbExpiration();
			CalculateActive();
			//CalculateDuration();
			DisplayActualNumbers();
			SetActualWarning();
			//clear actual grids
			_dgPatients.DataSource = null;
			_dgAdmissions.DataSource = null;
			_dgOutVisits.DataSource = null;
			_dgScatterNurse.DataSource = null;
			_dgAdmissionAncillaries.DataSource = null;
			_dgOutPatientAncillaries.DataSource = null;


		}

		private void DisplayActualNumbers()
		{
			_isExistsVisits = false;
			if (this._id.Text.Length == 0)
			{
				_actualPatients.Text = "";
				this._actualAdmissions.Text = "";
				this._actualOuPatientVisits.Text = "";
				this._actualScatterNurseVisits.Text = "";
				this._actualAdmissionAncillaries.Text = "";
				this._actualOutPatientAncillaries.Text = "";
				this._totalChargesAdmissionAncillaries.Text = "";
				this._totalChargesOutPatientAncillaries.Text = "";
				this._totalNetChargesAdmissionAncillaries.Text = "";
				this._totalNetChargesOutPatientAncillaries.Text = "";
			}
			else
			{
				int id = Convert.ToInt32(this._id.Text);

				int num = GetActualPatientNumber(id);
				if (num > 0)
					_isExistsVisits = true;
				_actualPatients.Text = num.ToString();

				num = GetActualAdmissionVisitCount(id);
				this._actualAdmissions.Text = num.ToString();

				num = GetActualOuPatientVisitCount(id);
				this._actualOuPatientVisits.Text = num.ToString();

				num = GetActualScatterNurseVisits(id);
				this._actualScatterNurseVisits.Text = num.ToString();

				num = GetActualAdmissionAncillariesCount(id);
				this._actualAdmissionAncillaries.Text = num.ToString();

				num = this.GetActualOutPatientAncillariesCount(id);
				this._actualOutPatientAncillaries.Text = num.ToString();
			}
		}

		private void SetActualWarning()
		{
			string message = "";
			Control ctl = Forms.Utils.GetControlByName("ID", this._form.Controls);
			TextBox proj = (TextBox)Forms.Utils.GetControlByName("ProjectedPatients", this._form.Controls);

			if (this._actualPatients.Text.Length == 0 || proj.Text.Length == 0)
			{
				this._form.errP.SetError(ctl, "");
				return;
			}

			int act = Convert.ToInt32(this._actualPatients.Text);
			int prj = Convert.ToInt32(proj.Text);
			if (prj < 1)
			{
				this._form.errP.SetError(ctl, "");
				return;
			}


			int percent = (act * 100) / prj;

			if (percent > 95)
			{
				if (act > prj)
				{
					int excd = act - prj;
					message = "Warning: Actual number of patients exceed projected by " + excd + ".";
				}
				else
					message = "Warning: Actual number of patients is " + percent + " percent of projected.";
			}
			this._form.errP.SetError(ctl, message);
		}

		private int GetActualScatterNurseVisits(int protoID)
		{
			int num = 0;
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT COUNT(Patient) FROM ScatterNurseHours " +
				" WHERE Protocol=" + protoID;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				num = (int)DataAccess.GetScalarObject(CommandType.Text, sql);
				return num;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Form could not get scatter nurse visits.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Scatter Nurse Visits Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private int GetActualOuPatientVisitCount(int protoID)
		{
			string message = "";
			int num = ProtocolUtils.GetActualOuPatientVisits(protoID, out message);

			if (message.Length > 0)
			{
				MessageBox.Show(this._form, message.ToString(), "Get Actual Out-Pateint Visit Count Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return num;
		}

		private int GetActualAdmissionVisitCount(int protoID)
		{
			string message = "";
			int num = ProtocolUtils.GetActualAdmissionVisitCount(protoID, out message);

			if (message.Length > 0)
			{
				MessageBox.Show(this._form, message.ToString(), "Get Actual Admission Visit Count Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return num;
		}

		private decimal GetActualAdmissionAncillariesNetCharges(int protoID)
		{
			string file = CremaConstants.ReportsDirecotry + "AdmissionAncillayRateExceptions";
			StreamWriter sw = new StreamWriter(file, false);
			StringBuilder sb = new StringBuilder();
			bool exclusion = false;
			int id = 0;
			decimal net = 0;
			decimal totNet = 0;
			decimal charge = 0;
			DateTime date = new DateTime(0);
			int center = 0;
			string line = "";

			string sql = "SELECT a.ID, a.TestDate,a.CostCenter,a.Charge " +
				" FROM AncillaryAdmission a, ProtocolVisitAdmission p" +
				" WHERE p.Protocol=" + protoID +
				" AND a.Visit = p.ID";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				while (reader.Read())
				{
					id = reader.GetInt32(0);
					date = reader.GetDateTime(1);
					center = reader.GetInt32(2);
					charge = reader.GetDecimal(3);
					net = GetNetCharge(date, center, charge);
					if (net == 0)
					{
						exclusion = true;
						line = "ID: " + id.ToString() + ", Cost Center ID: " + center +
							", Charge: " + charge.ToString();
						sw.WriteLine(line);
					}
					totNet += net;
				}
				return totNet;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving admission ancillary net charges!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Actual Admission Ancillary Net Charges Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				if (sw != null)
					sw.Close();
				if (exclusion)
				{
					sb.Append("There were exclusions!");
					sb.Append(Environment.NewLine);
					sb.Append("The report was saved as a text file in the '" + CremaConstants.ReportsDirecotry + "' directory.");
					sb.Append(Environment.NewLine);
					sb.Append("Do you want to print the exclusion report?");
					if (MessageBox.Show(this._form, sb.ToString(), "Exclusion Report", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
						PrintExclusions(file);
				}
			}

		}

		private decimal GetNetCharge(DateTime date, int center, decimal charge)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT Rate " +
				" FROM AncillaryRate " +
				" WHERE CostCenter =" + center +
				" AND (StartDate <='" + date.ToShortDateString() + "'" +
				" AND EndDate >='" + date.ToShortDateString() + "')";

			decimal rate = 0;
			decimal net = 0;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					rate = reader.GetDecimal(0);
					net = rate * charge;
				}

				return net;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving ancillary rate!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Ancillary Rate Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private decimal GetActualAdmissionAncillariesGrossCharge(int protoID)
		{
			StringBuilder sb = new StringBuilder();
			decimal charge = 0;

			string sql = "SELECT SUM(a.Charge) " +
				" FROM AncillaryAdmission a, ProtocolVisitAdmission p" +
				" WHERE p.Protocol=" + protoID +
				" AND a.Visit = p.ID";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					if (!reader.IsDBNull(0))
						charge = reader.GetDecimal(0);
				}
				return charge;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving actual admission ancillary charges!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Actual Admission Ancillary Charges Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private int GetActualAdmissionAncillariesCount(int protoID)
		{
			StringBuilder sb = new StringBuilder();
			int num = 0;

			string sql = "SELECT COUNT(a.Visit) " +
				" FROM AncillaryAdmission a, ProtocolVisitAdmission p" +
				" WHERE p.Protocol=" + protoID +
				" AND a.Visit = p.ID";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					if (!reader.IsDBNull(0))
						num = reader.GetInt32(0);
				}
				return num;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving actual admission ancillaries count!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Actual Admission Ancillaries Count Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private decimal GetActualOutPatientAncillariesNetCharges(int protoID)
		{
			string file = CremaConstants.ReportsDirecotry + "OutPatientAncillayRateExceptions";
			StreamWriter sw = new StreamWriter(file, false);
			StringBuilder sb = new StringBuilder();
			bool exclusion = false;
			int id = 0;
			decimal net = 0;
			decimal totNet = 0;
			decimal charge = 0;
			DateTime date = new DateTime(0);
			int center = 0;
			string line = "";

			string sql = "SELECT a.ID, a.TestDate,a.CostCenter,a.Charge " +
				" FROM AncillaryOutPatient a, ProtocolVisitOutPatient p" +
				" WHERE p.Protocol=" + protoID +
				" AND a.Visit = p.ID";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				while (reader.Read())
				{
					id = reader.GetInt32(0);
					date = reader.GetDateTime(1);
					center = reader.GetInt32(2);
					charge = reader.GetDecimal(3);
					net = GetNetCharge(date, center, charge);
					if (net == 0)
					{
						exclusion = true;
						line = "ID: " + id.ToString() + ", Cost Center ID: " + center +
							", Charge: " + charge.ToString();
						sw.WriteLine(line);
					}
					totNet += net;
				}
				return totNet;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving admission ancillary net charges!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Actual Admission Ancillary Net Charges Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				if (sw != null)
					sw.Close();
				if (exclusion)
				{
					sb.Append("There were exclusions!");
					sb.Append(Environment.NewLine);
					sb.Append("The report was saved as a text file in the '" + CremaConstants.ReportsDirecotry + "' directory.");
					sb.Append(Environment.NewLine);
					sb.Append("Do you want to print the exclusion report?");
					if (MessageBox.Show(this._form, sb.ToString(), "Exclusion Report", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
						PrintExclusions(file);
				}
			}
		}

		private int GetActualOutPatientAncillariesCount(int protoID)
		{
			StringBuilder sb = new StringBuilder();
			int num = 0;

			string sql = "SELECT COUNT(a.Visit) " +
				" FROM AncillaryOutPatient a, ProtocolVisitOutPatient p" +
				" WHERE p.Protocol=" + protoID +
				" AND a.Visit = p.ID";

			IDataReader reader = null;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					if (!reader.IsDBNull(0))
						num = reader.GetInt32(0);
				}
				return num;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving actual admission ancillary count!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Actual Admission Ancillary Count Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private decimal GetActualOutPatientAncillariesGrossCharge(int protoID)
		{
			StringBuilder sb = new StringBuilder();
			decimal charge = 0;

			string sql = "SELECT SUM(a.Charge) " +
				" FROM AncillaryOutPatient a, ProtocolVisitOutPatient p" +
				" WHERE p.Protocol=" + protoID +
				" AND a.Visit = p.ID";

			IDataReader reader = null;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					if (!reader.IsDBNull(0))
						charge = reader.GetDecimal(0);
				}
				return charge;
			}
			catch (Exception ex)
			{
				sb.Append("Error in retrieving actual admission ancillaries gross charge!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Actual Admission Ancillaries Gross Charge Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private int GetActualPatientNumber(int protoID)
		{
			string message = "";
			int num = ProtocolUtils.GetActualPatientNumber(protoID, out message);

			if (message.Length > 0)
			{
				MessageBox.Show(this._form, message.ToString(), "Get Actual Pateint Count Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return num;
		}


		//display the investigator screen in new mode
		private void DisplayNewInvestigForm()
		{
			StringBuilder sb = new StringBuilder();
			FormInvestigator finv = new FormInvestigator();

			//need to create instance for bl			
			FormInfoBase fi = this._formMain.GetFormInfo(30, true);

			//check for permission
			Permission permission = Forms.FormSecurity.GetFormAccess(fi, LoginForm.ApplicationSecurity.ApplicationUser);
			if (permission == Permission.AccessDenied)
			{
				MessageBox.Show(this._form, "You do not have access rights for form: " + fi.Name, "Access Denied");
				return;
			}

			DataTable dt = Forms.Utils.GetTableSchema(fi.TableName, null);
			Hashtable ht = this._formMain.GetFormsConfigUserOptions();

			BLFormInvestigatorDialolgImpl bl = new BLFormInvestigatorDialolgImpl(this._formMain, finv, fi, dt, permission, ht);

			//create controller
			FormBaseControllerImpl ctlr = new FormBaseControllerImpl(finv, bl);
			if (!bl.Initialize())
			{
				sb.Append("Could not load form!");
				sb.Append(Environment.NewLine);
				sb.Append(Constants.NotifySupport);
				MessageBox.Show(this._form, sb.ToString(), "Loading Form Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finv.Controller = ctlr;

			bl.GridView += new BusinessLogicEvents.BLGridViewEventHandler(this._formMain.OnGridView);
			bl.TableChange += new ctsu.BaseForms.BusinessLogicEvents.BLTableChangeEventHandler(this._formMain.OnTableChange);

			finv.ShowDialog(this._form);
			if (finv.DialogResult == DialogResult.OK)
			{


				FormGridMeta fgm = (FormGridMeta)this._formInfo.GridMeta["ProtocolStaff"];
				FormGridColumnMeta fgcm = (FormGridColumnMeta)fgm.GridColumns["InvestigatorID"];
				IBLFormGridBase fgbl = (IBLFormGridBase)this._gridBLs["ProtocolStaff"];

				UserGrid ug = (UserGrid)Forms.Utils.GetControlByName("ProtocolStaff", this._form.Controls);
				GridStyleInfo gsi = ug.Grid.ColStyles[2];

				fgbl.BindGridColumn(fgcm, gsi);
			}
		}

		private void PrintExclusions(string file)
		{
			DataTable dt = new DataTable();
			DataColumn dc = new DataColumn("Exception", typeof(string));
			dc.Caption = "Exception";
			dc.ExtendedProperties.Add("Width", 750);
			dt.Columns.Add(dc);

			try
			{
				using (StreamReader sr = new StreamReader(file))
				{
					string line;
					while ((line = sr.ReadLine()) != null)
					{
						DataRow dr = dt.NewRow();
						dr["Exception"] = line;
						dt.Rows.Add(dr);
					}
				}
				if (dt.Rows.Count > 0)
				{
					string[] title = new string[1];
					title[0] = file;

					PrintingUtils pu = new PrintingUtils(dt, title, this._form, false);
					pu.Initialize();
				}
			}
			catch
			{
			}


		}

		private void PrintGridActual(object sender)
		{
			Button button = (Button)sender;
			int indx = this._tab2.SelectedIndex;
			_dgPrint = null;
			switch (indx)
			{
				case 0:
					_dgPrint = _dgPatients;
					_subTitle = "Patients";
					break;
				case 1:
					_dgPrint = _dgAdmissions;
					_subTitle = "Admissions";
					break;
				case 2:
					_dgPrint = _dgOutVisits;
					_subTitle = "Outpatient Visits";
					break;
				case 3:
					_dgPrint = _dgScatterNurse;
					_subTitle = "Scatter Nurse Hour Visits";
					break;
				case 4:
					_dgPrint = _dgAdmissionAncillaries;
					_subTitle = "Admission Ancillaries";
					break;
				case 5:
					_dgPrint = _dgOutPatientAncillaries;
					_subTitle = "Outpatient Ancillaries";
					break;
			}
			if (_dgPrint.DataSource == null)
			{
				MessageBox.Show("Nothing to print!");
				return;
			}
			_dtPrint = (DataTable)_dgPrint.DataSource;
			if (_dtPrint.Rows.Count == 0)
			{
				MessageBox.Show("Nothing to print!");
				return;
			}
			button.Enabled = false;

			this._pDoc = new PrintDocument();
			this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (_pDlg.ShowDialog(this._form) == DialogResult.Cancel)
			{
				button.Enabled = true;
				return;
			}

			this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);
			_page = 1;
			_startRow = 0;
			this._pDoc.Print();

			button.Enabled = true;
		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 25;
			float topMargin = 25;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;
			float adjLineHeight = 0;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			Forms.PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			#region title
			StringBuilder sbCrit = new StringBuilder();
			FieldContext fc = (FieldContext)this._fcManager.Item("ID");
			string id = fc.Control.Text;
			//fc = (FieldContext)this._fcManager.Item("SPID");
			//string spid = fc.Control.Text;
			fc = (FieldContext)this._fcManager.Item("ProtocolNumber");
			string protoNumber = fc.Control.Text;

			string protoTitle = "Protocol #: " + protoNumber +
				";   ID: " + id; //+
				//";   SPID: " + spid;
			//print title and subtitle
			if (this._page == 1)
			{
				Forms.PrintingUtils.PrintCenter("GCRC - Protocol Actuals Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics);
				Forms.PrintingUtils.PrintCenter(protoTitle, e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics);
				Forms.PrintingUtils.PrintCenter(this._subTitle, e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("GCRC - Protocol Actuals Report - continued");
				Forms.PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics);
				Forms.PrintingUtils.PrintCenter(protoTitle, e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics);
				Forms.PrintingUtils.PrintCenter(this._subTitle, e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;
			#endregion title

			#region heading
			int[] colWidth = new int[this._dtPrint.Columns.Count];
			int[] colStart = new int[this._dtPrint.Columns.Count];
			int totWidth = 2;
			int i = 0;
			int width = 0;

			RectangleF rec = new RectangleF();
			gfx.DrawRectangle(Pens.Black, 0, yPos, (pageWidth - 25), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 0, yPos, pageWidth - 25, lineHeight);

			foreach (DataColumn dc in this._dtPrint.Columns)
			{
				colStart[i] = totWidth + 2;

				width = Convert.ToInt32(dc.ExtendedProperties["Width"]);
				totWidth += width;
				colWidth[i] = width;

				Forms.PrintingUtils.SetRectangle(ref rec, colStart[i], yPos, lineHeight, colWidth[i]);
				gfx.DrawString(dc.Caption, ColumnHeadFont, Brushes.Black, rec);
				i++;
			}
			yPos += lineHeight;
			#endregion heading

			#region body
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			DataRow dr;
			int numLines = 0;
			for (int row = _startRow; row < _dtPrint.Rows.Count; row++)
			{
				dr = _dtPrint.Rows[row];

				//get the field with most number of lines
				numLines = PrintingUtils.GetNumberLinesRow(dr, e.Graphics, prntFont, lineHeight, colWidth);

				if (curLine + numLines >= maxLines)
				{
					_startRow = row;
					this._page++;
					e.HasMorePages = true;
					return;
				}

				adjLineHeight = lineHeight * numLines;
				int j = 0;
				string sVal = "";
				foreach (DataColumn dc in this._dtPrint.Columns)
				{
					Forms.PrintingUtils.SetRectangle(ref rec, colStart[j], yPos, adjLineHeight, colWidth[j]);
					switch (dc.DataType.ToString())
					{
						case "System.String":
							sVal = dr[dc.ColumnName].ToString().Trim();
							break;
						case "System.Int32":
							sVal = dr[dc.ColumnName].ToString();
							break;
						case "System.DateTime":
							sVal = ((DateTime)dr[dc.ColumnName]).ToString("MM/dd/yyyy");
							break;
						case "System.Decimal":
							sVal = ((decimal)dr[dc.ColumnName]).ToString("#,###.##");
							break;
						case "System.Boolean":
							sVal = dr[dc.ColumnName].ToString();
							break;
					}
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);
					j++;
				}

				gfx.DrawRectangle(Pens.Black, 0, yPos, (pageWidth - 25), adjLineHeight);
				yPos += adjLineHeight;
				curLine += numLines;
			}
			#endregion body
		}

		private void _incomplete_Click(object sender, EventArgs e)
		{
			MessageBox.Show(this._form, "The Incomplete checkbox cannot be changed by the user", "Read Only Checkbox", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

		
	}
}
